﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NMA.Web.Areas.Admin.Models
{
    /// <summary>
    /// Referenced from Mr.ThoaiNguyen (my colleage)
    /// http://nthoai.blogspot.com/
    /// </summary>
    public class PagingModel
    {
        private const int DefaultDisplayingPage = 10;
        /// <summary>
        /// Gets or sets the index of the page. 
        /// It's COUNT from 1
        /// </summary>
        /// <value>The index of the page.</value>
        public int PageIndex { get; private set; }
        public int PageSize { get; private set; }
        public int TotalCount { get; private set; }
        public string PageActionLink { get; private set; }
        public int PagesToDisplay { get; private set; }
        public string CssClass { get; private set; }

        public PagingModel(int pageIndex, int pageSize, int totalCount, string pageActionLink, string cssClass)
        {
            PageIndex = pageIndex;
            PageSize = pageSize;
            TotalCount = totalCount;
            PageActionLink = pageActionLink;
            CssClass = cssClass;
            PagesToDisplay = TotalPages < DefaultDisplayingPage ? TotalPages : DefaultDisplayingPage;
        }

        public int TotalPages
        {
            get
            {
                return TotalCount / PageSize + (TotalCount % PageSize == 0 ? 0 : 1);
            }
        }
        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 1);
            }
        }

        public bool HasNextPage
        {
            get
            {
                return (PageIndex < TotalPages);
            }
        }

        public int MinItemIndexOfCurrentPage
        {
            get
            {
                if (0 == TotalCount)
                {
                    return 0;
                }
                return ((PageIndex - 1) * PageSize) + 1;
            }
        }

        public int MaxItemIndexOfCurrentPage
        {
            get
            {
                return System.Math.Min((PageIndex) * PageSize, TotalCount);
            }
        }

        public int MaxPageIndexToDisplay
        {
            get
            {
                var expectedMaxPageIndex = PageIndex + PagesToDisplay / 2;
                if (expectedMaxPageIndex > TotalPages)
                {
                    return TotalPages;
                }
                var maxPageIndex = (PagesToDisplay > expectedMaxPageIndex ? PagesToDisplay : expectedMaxPageIndex);
                return maxPageIndex;
            }
        }

        public int MinPageIndexForDisplaying
        {
            get
            {
                return (MaxPageIndexToDisplay - PagesToDisplay + 1);
            }
        }
    }
}